package servlets;

import java.io.IOException;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import usecases.GestionConcoursPizza;
import util.Constante;
import domaine.ConcoursPizza;

/**
 * Servlet implementation class salleDAttente
 */
@WebServlet(name = "creerpartie.html")
public class CreerPartie extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	private GestionConcoursPizza gestionConcoursPizza;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("salledattente.html");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if(request.getSession().getAttribute("apprenti")==null){
			response.sendRedirect("index.html");
			return;
		}	
		String nomDeLaPartie = request.getParameter("nomPartie");
		if (nomDeLaPartie.isEmpty()) {
			response.sendRedirect("salledattente.html");
			return;
		}

		final ConcoursPizza concours = new ConcoursPizza(nomDeLaPartie);

		final Map<String, ConcoursPizza> lesConcours = (Map<String, ConcoursPizza>) this
				.getServletContext().getAttribute("lesConcours");

		lesConcours.put(concours.getNomConcours(), concours);

		// lancer le timer avant le debut de la partie
		Timer timer = new Timer();
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				if (concours.getIdConcours() == 0) {
					try {

						ConcoursPizza concoursCree = gestionConcoursPizza
								.creerPartie(concours);
						lesConcours.put(concoursCree.getNomConcours(),
								concoursCree);
					} catch (Throwable t) {
						lesConcours.remove(concours.getNomConcours());
					}
				}

			}
		};
		timer.schedule(task, Constante.TEMPS_DEBUT_PARTIE * 1000);

		response.sendRedirect(response.encodeRedirectURL("salledattente.html"));
	}

}
